package com.antis.olsl.data.stock.store;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.antis.olsl.arouterlib.DataRoutePath;
import com.antis.olsl.base.BaseFragment;
import com.antis.olsl.base.utils.LogUtils;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.data.R;
import com.antis.olsl.data.adapter.BrandQueryAdapter;
import com.antis.olsl.data.adapter.CategoryQueryAdapter;
import com.antis.olsl.data.adapter.ProductQueryAdapter;
import com.antis.olsl.data.databinding.FragmentStockStoreBinding;
import com.antis.olsl.data.response.GetBrandInventoryListResp;
import com.antis.olsl.data.response.GetCategoryInventoryListResp;
import com.antis.olsl.data.response.GetProductInventoryListResp;
import com.antis.olsl.data.stock.StockQueryContract;
import com.antis.olsl.data.stock.StockQueryPresenter;
import com.antis.olsl.library.bean.MenuInfo;
import com.antis.olsl.library.dialog.ChooseSalesroomDialog;
import com.antis.olsl.library.dialog.ChooseTypeDialog;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.library.widget.ChooseSalesroomView;
import com.antis.olsl.library.widget.MyInputSearchLayout;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据查询-门店Fragment
 *
 * @author hhh
 */
public class StockStoreFragment extends BaseFragment<FragmentStockStoreBinding> implements View.OnClickListener,
        MyInputSearchLayout.TextChangedListener, ChooseSalesroomView.ChooseSalesroomListener,
        ChooseSalesroomDialog.ChooseSalesroomListener, StockQueryContract.View {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    private ArrayList<MenuInfo> menuInfos = new ArrayList<>();
    private MenuInfo menuInfo;

    private ArrayList<MenuInfo> sortInfoList = new ArrayList<>();
    private MenuInfo sortMenuInfo;

    private ChooseTypeDialog mDialog;
    private String searchText = "";
    private int pageNum = 0;

    private boolean isEnd;

    private ChooseSalesroomDialog chooseSalesroomDialog;
    private String salesRoomIds = "";
    private SalesroomOrWarehouseInfo mInfo;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();

    private List<GetProductInventoryListResp.ContentBean.ProductListBean> mProductQueryList = new ArrayList<>();
    private List<GetBrandInventoryListResp.ContentBean.BrandListBean> mBrandQueryList = new ArrayList<>();
    private List<GetCategoryInventoryListResp.ContentBean.CategoryListBean> mCategoryQueryList = new ArrayList<>();
    private ProductQueryAdapter mProductQueryAdapter;
    private BrandQueryAdapter mBrandQueryAdapter;
    private CategoryQueryAdapter mCategoryQueryAdapter;

    private StockQueryPresenter mPresenter;

    public StockStoreFragment() {
    }

    public static StockStoreFragment newInstance(String param1, String param2) {
        StockStoreFragment fragment = new StockStoreFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected FragmentStockStoreBinding getViewBinding() {
        return FragmentStockStoreBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initView(View view) {
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(null);
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setChooseSalesroomListener(this);

        viewBinding.layoutChooseType.setOnClickListener(this);
        viewBinding.layoutChooseSort.setOnClickListener(this);

        viewBinding.layoutSearchInput.myInputSearchLayout.setHintText("请输入商品条码/名称");
        viewBinding.layoutSearchInput.myInputSearchLayout.setListener(this);
        initMenu();
        initSort();
        initPresenter();

        initAdapter();
    }

    private void initMenu() {
        MenuInfo info = new MenuInfo();
        info.id = "1";
        info.name = "单品";
        info.choose = true;
        menuInfos.add(info);

        MenuInfo info2 = new MenuInfo();
        info2.id = "2";
        info2.name = "品牌";
        info2.choose = false;
        menuInfos.add(info2);

        MenuInfo info3 = new MenuInfo();
        info3.id = "3";
        info3.name = "品类";
        info3.choose = false;
        menuInfos.add(info3);

        menuInfo = info;
    }

    private void initSort() {
        MenuInfo info = new MenuInfo();
        info.id = "0";
        info.name = "全部分类";
        info.choose = true;
        sortInfoList.add(info);

        MenuInfo info1 = new MenuInfo();
        info1.id = "1";
        info1.name = "一级分类";
        info1.choose = false;
        sortInfoList.add(info1);

        MenuInfo info2 = new MenuInfo();
        info2.id = "2";
        info2.name = "二级分类";
        info2.choose = false;
        sortInfoList.add(info2);

        MenuInfo info3 = new MenuInfo();
        info3.id = "3";
        info3.name = "三级分类";
        info3.choose = false;
        sortInfoList.add(info3);

        MenuInfo info4 = new MenuInfo();
        info4.id = "4";
        info4.name = "四级分类";
        info4.choose = false;
        sortInfoList.add(info4);

        MenuInfo info5 = new MenuInfo();
        info5.id = "5";
        info5.name = "五级分类";
        info5.choose = false;
        sortInfoList.add(info5);

        sortMenuInfo = info;
    }

    private void initPresenter() {
        mPresenter = new StockQueryPresenter();
        mPresenter.takeView(this);
    }

    private void initAdapter() {
        mProductQueryAdapter = new ProductQueryAdapter(R.layout.item_product_query_list, mProductQueryList);
        mBrandQueryAdapter = new BrandQueryAdapter(R.layout.item_product_query_list, mBrandQueryList);
        mCategoryQueryAdapter = new CategoryQueryAdapter(R.layout.item_product_query_list, mCategoryQueryList);
        viewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));

        viewBinding.recyclerView.setAdapter(mProductQueryAdapter);

        initRecyclerMore();

        initRecyclerItemClick();
    }

    private void initRecyclerMore() {
        mProductQueryAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                viewBinding.recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isEnd) {
                            mProductQueryAdapter.getLoadMoreModule().loadMoreEnd();
                        } else {
                            flushData();
                        }
                    }
                }, 200);
            }
        });

        mBrandQueryAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                viewBinding.recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isEnd) {
                            mBrandQueryAdapter.getLoadMoreModule().loadMoreEnd();
                        } else {
                            flushData();
                        }
                    }
                }, 200);
            }
        });

        mCategoryQueryAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                viewBinding.recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isEnd) {
                            mCategoryQueryAdapter.getLoadMoreModule().loadMoreEnd();
                        } else {
                            flushData();
                        }
                    }
                }, 200);
            }
        });
    }

    private void initRecyclerItemClick() {
        mProductQueryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String productCode = mProductQueryList.get(position).productCode;
                ARouter.getInstance()
                        .build(DataRoutePath.ACTIVITY_PRODUCT_DETAIL)
                        .withString("productCode", productCode)
                        .navigation();
            }
        });

        mBrandQueryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String brandCode = mBrandQueryList.get(position).brandCode;
                ARouter.getInstance()
                        .build(DataRoutePath.ACTIVITY_BRAND_DETAIL)
                        .withString("brandCode", brandCode)
                        .navigation();
            }
        });

        mCategoryQueryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                String categoryName = mCategoryQueryList.get(position).categoryName;
                ARouter.getInstance()
                        .build(DataRoutePath.ACTIVITY_CATEGORY_DETAIL)
                        .withString("categoryName", categoryName)
                        .navigation();
            }
        });
    }

    private void flushData() {
        Map<String, Object> map = new HashMap<>(6);
        map.put("inventoryId", salesRoomIds);
        map.put("flag", 0);
        map.put("keyword", searchText);
        map.put("pageNum", pageNum);
        map.put("pageSize", 10);
        if (null != menuInfo) {
            if (menuInfo.id.equals("1")) {
                mPresenter.getProductInventoryList(map);
            } else if (menuInfo.id.equals("2")) {
                mPresenter.getBrandInventoryList(map);
            } else {
                map.put("categoryLevel", sortMenuInfo.id);
                mPresenter.getCategoryInventoryList(map);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mDialog) {
            mDialog.dismiss();
        }
        if (null != chooseSalesroomDialog) {
            chooseSalesroomDialog.dismiss();
        }
    }

    @Override
    protected void loadData() {
        flushData();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.layout_choose_type) {
            chooseType();
        } else if (id == R.id.layout_choose_sort) {
            chooseSortType();
        }
    }

    private void chooseType() {
        mDialog = new ChooseTypeDialog(getContext(), "选择类型", menuInfos, new ChooseTypeDialog.ChooseTypeListener() {
            @Override
            public void onChooseTypeListener(int selectedIndex) {
                menuInfo = menuInfos.get(selectedIndex);
                LogUtils.e("menuInfo= " + menuInfo.name);
                viewBinding.textType.setText(menuInfo.name);

                setRecyclerLabel(menuInfo.id);
                pageNum = 0;
                flushData();
            }
        });
    }

    private void chooseSortType() {
        mDialog = new ChooseTypeDialog(getContext(), "选择分类", sortInfoList, new ChooseTypeDialog.ChooseTypeListener() {
            @Override
            public void onChooseTypeListener(int selectedIndex) {
                sortMenuInfo = sortInfoList.get(selectedIndex);
                LogUtils.e("sortMenuInfo= " + sortMenuInfo.name);
                viewBinding.textSort.setText(sortMenuInfo.name);

                pageNum = 0;
                flushData();
            }
        });
    }

    private void setRecyclerLabel(String type) {
        if (type.equals("1")) {
            viewBinding.textLabel.setText("商品编码");
            viewBinding.textLabel2.setText("商品名称");
            viewBinding.textLabel3.setText("小库存量");
            viewBinding.textLabel4.setText("库存总量");
            viewBinding.layoutChooseSort.setVisibility(View.GONE);
        } else if (type.equals("2")) {
            viewBinding.textLabel.setText("品牌编码");
            viewBinding.textLabel2.setText("品牌名称");
            viewBinding.textLabel3.setText("小库存量");
            viewBinding.textLabel4.setText("库存总量");
            viewBinding.layoutChooseSort.setVisibility(View.GONE);
        } else {
            viewBinding.textLabel.setText("品类名称");
            viewBinding.textLabel2.setText("陈列量");
            viewBinding.textLabel3.setText("小库存量");
            viewBinding.textLabel4.setText("库存总量");
            viewBinding.layoutChooseSort.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onTextChangeListener(String text) {
        pageNum = 0;
        searchText = text;
        flushData();
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getSalesroom();
        } else {
            chooseSalesroomDialog = new ChooseSalesroomDialog(getContext(), salesroomInfos, StockStoreFragment.this);
        }
    }

    private void getSalesroom() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {

    }

    @Override
    public void onChooseSalesroomListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        salesroomInfos = sourceInofs;
        selectedSalesroomInfos = choosedFiledInfos;
        if (selectedIndex == -1) {
            salesRoomIds = "";
            viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(null);
        } else {
            salesRoomIds = filterIds();
        }
        pageNum = 0;
        flushData();
    }

    private String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = salesroomInfos;
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {
            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }

        if (infos.size() > 0) {
            mInfo = infos.get(0);
        }
        viewBinding.layoutChooseSalesroom.chooseSalesroomView.setSalesroomInfos(infos);
        return ids;
    }

    @Override
    public void getSalesroomOrWarehouseInfoListSuccess(List<SalesroomOrWarehouseInfo> list) {
        salesroomInfos.clear();
        salesroomInfos.addAll(list);
        LogUtils.e("getSalesroomOrWarehouseInfoListSuccess resp= " + list.size());

        chooseSalesroomDialog = new ChooseSalesroomDialog(getContext(), salesroomInfos, this);
    }

    @Override
    public void getSalesroomOrWarehouseInfoListFailure(String msg) {
        LogUtils.e("getSalesroomOrWarehouseInfoListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(getContext(), msg);
    }

    @Override
    public void getProductInventoryListSuccess(GetProductInventoryListResp resp) {
        viewBinding.textProductAmount.setText(resp.content.productCount + "");
        viewBinding.textTotalPurchasePrice.setText(resp.content.totalCost + "");
        viewBinding.textTotalPrice.setText(resp.content.totalPrice + "");
        if (pageNum == 0) {
            mProductQueryList.clear();
        }
        mProductQueryList.addAll(resp.content.productList);
        if (resp.content.productList.size() >= 10) {
            isEnd = false;
            pageNum += 1;
        } else {
            isEnd = true;
        }
        viewBinding.recyclerView.setAdapter(mProductQueryAdapter);
        mProductQueryAdapter.setList(mProductQueryList);
        mProductQueryAdapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void getProductInventoryListFailure(String msg) {
        LogUtils.e("getProductInventoryListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(mActivity, msg);
    }

    @Override
    public void getBrandInventoryListSuccess(GetBrandInventoryListResp resp) {
        viewBinding.textProductAmount.setText(resp.content.productCount + "");
        viewBinding.textTotalPurchasePrice.setText(resp.content.totalCost + "");
        viewBinding.textTotalPrice.setText(resp.content.totalPrice + "");
        if (pageNum == 0) {
            mBrandQueryList.clear();
        }
        mBrandQueryList.addAll(resp.content.brandList);
        if (resp.content.brandList.size() >= 10) {
            isEnd = false;
            pageNum += 1;
        } else {
            isEnd = true;
        }
        viewBinding.recyclerView.setAdapter(mBrandQueryAdapter);
        mBrandQueryAdapter.setList(mBrandQueryList);
        mBrandQueryAdapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void getBrandInventoryListFailure(String msg) {
        LogUtils.e("getBrandInventoryListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(mActivity, msg);
    }

    @Override
    public void getCategoryInventoryListSuccess(GetCategoryInventoryListResp resp) {
        viewBinding.textProductAmount.setText(resp.content.productCount + "");
        viewBinding.textTotalPurchasePrice.setText(resp.content.totalCost + "");
        viewBinding.textTotalPrice.setText(resp.content.totalPrice + "");
        if (pageNum == 0) {
            mCategoryQueryList.clear();
        }
        mCategoryQueryList.addAll(resp.content.categoryList);
        if (resp.content.categoryList.size() >= 10) {
            isEnd = false;
            pageNum += 1;
        } else {
            isEnd = true;
        }
        viewBinding.recyclerView.setAdapter(mCategoryQueryAdapter);
        mCategoryQueryAdapter.setList(mCategoryQueryList);
        mCategoryQueryAdapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void getCategoryInventoryListFailure(String msg) {
        LogUtils.e("getCategoryInventoryListFailure msg= " + msg);
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(mActivity, msg);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }
}